from machine import Pin
from machine import FPIOA
from machine import UART
import time
import _thread

# 创建FPIOA对象，用于初始化引脚功能配置
fpioa = FPIOA()

# 打印所有引脚的配置状态
fpioa.help()

# 1.设置串口2
fpioa.set_function(11, FPIOA.UART2_TXD)
fpioa.set_function(12, FPIOA.UART2_RXD)
# 初始化 UART2，配置波特率为 115200，8 位数据位，无校验位，1 个停止位
u2 = UART(UART.UART2, baudrate=115200, bits=UART.EIGHTBITS, parity=UART.PARITY_NONE, stop=UART.STOPBITS_ONE)

# 2.设置引脚功能，将指定的引脚配置为普通GPIO功能,
fpioa.set_function(62,FPIOA.GPIO62)
fpioa.set_function(20,FPIOA.GPIO20)
fpioa.set_function(63,FPIOA.GPIO63)
# 实例化Pin62, Pin20, Pin63为输出，分别用于控制红、绿、蓝三个LED灯
LED_R = Pin(62, Pin.OUT, pull=Pin.PULL_NONE, drive=7)  # 红灯
LED_G = Pin(20, Pin.OUT, pull=Pin.PULL_NONE, drive=7)  # 绿灯
LED_B = Pin(63, Pin.OUT, pull=Pin.PULL_NONE, drive=7)  # 蓝灯
# 板载RGB灯是共阳结构，设置引脚为高电平时关闭灯，低电平时点亮灯
# 初始化时先关闭所有LED灯
LED_R.high()  # 关闭红灯
LED_G.high()  # 关闭绿灯
LED_B.high()  # 关闭蓝灯

# 定义一个无参函数
def usart2_func():
    while True:
        u2.write("UART2 test.\r\n") # 通过 UART2 发送数据
        time.sleep(1)

def print_func():
    while True:
        print("Hello, MicroPython!")
        time.sleep(1)

def func(name):
    while 1:
#        print("hello {}".format(name))
        if name == "RED":
          if LED_R.value():
            LED_R.off()
          else:
            LED_R.on()
        elif name == "GREEN":
          if LED_G.value():
            LED_G.off()
          else:
            LED_G.on()
        elif name == "BLUE":
          if LED_B.value():
            LED_B.low()
          else:
            LED_B.high()
        time.sleep_ms(500)

# 启动线程
_thread.start_new_thread(usart2_func, ())
_thread.start_new_thread(print_func, ())

_thread.start_new_thread(func,("RED",))
_thread.start_new_thread(func,("GREEN",))
_thread.start_new_thread(func,("BLUE",))

while True:
    pass
